package com.yan.common.user.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yan.common.login.model.LoginUser;
import com.yan.common.user.mapper.SysUserMapper;
import com.yan.common.user.mapper.UserRoleRelMapper;
import com.yan.common.user.model.SysUser;
import com.yan.common.user.model.SysUserKey;
import com.yan.common.user.model.UserRoleRel;
import com.yan.common.user.model.UserRoleRelExample;
import com.yan.core.annotation.MapperInject;
import com.yan.core.controller.BaseController;
import com.yan.core.model.MsgModel;
import com.yan.core.model.PageModel;

/**
 * 名称：UserController<br>
 *
 * 描述：用户管理模块<br>
 *
 * @author Yanzheng 严正<br>
 *         时间：<br>
 *         2017-09-07 15:43:05<br>
 *         版权：<br>
 *         Copyright 2017 <a href="https://github.com/micyo202" target=
 *         "_blank">https://github.com/micyo202</a>. All rights reserved.
 */
@Controller
@RequestMapping("/common/user")
public class UserController extends BaseController {

	@MapperInject(SysUserMapper.class)
	private SysUserMapper mapper;

	@RequestMapping("/manage")
	public String manage() {
		return "common/user/manage";
	}

	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public PageModel<HashMap<String, Object>> list(@RequestParam HashMap<String, Object> params) {
		PageModel pageModel = new PageModel();
		String offset = (String) params.get("offset");
		String limit = (String) params.get("limit");
		Integer iter = Integer.parseInt(offset);
		Integer limitInt = Integer.parseInt(limit);
		String end = (iter + limitInt) + "";
		params.put("limit", end);
		// 查询列表
		List<HashMap<String, Object>> listResult = mapper.queryUserList(params);
		// 统计查询
		Integer count = mapper.queryUserCount(params);
		pageModel.setRows(listResult);
		pageModel.setTotal(count);
		return pageModel;
	}

	/**
	 * 用户对应角色保存方法<br>
	 *
	 * @param userId
	 *            用户Id
	 * @param roleStr
	 *            角色列表字符串
	 * @return MsgModel 消息模型
	 */
	@RequestMapping(value = "/roleSave", method = RequestMethod.POST)
	@ResponseBody
	public MsgModel roleSave(String userId, String roleStr) {
		List<String> roleIds = Arrays.asList(roleStr.split(","));
		UserRoleRelMapper mapper = this.getMapper(UserRoleRelMapper.class);

		// 先清除历史数据
		UserRoleRelExample example = new UserRoleRelExample();
		example.createCriteria().andUserIdEqualTo(userId);
		mapper.deleteByExample(example);

		// 添加
		for (String roleId : roleIds) {
			if (!this.isNull(roleId.trim())) {
				UserRoleRel userRoleRel = new UserRoleRel();
				userRoleRel.setRelId(this.getUUID());
				userRoleRel.setUserId(userId);
				userRoleRel.setRoleId(roleId);
				mapper.insertSelective(userRoleRel);
			}
		}
		return this.resultMsg("保存成功");
	}

	@RequestMapping("/upload")
	@ResponseBody
	public String upload(HttpServletRequest request) {
		List<String> fileNames = this.fileUpLoad(request);
		System.out.println(fileNames);
		return "success";
	}

	/**
	 * 用户删除
	 *
	 */
	@RequestMapping(value = "/deleteUser", method = RequestMethod.POST)
	@ResponseBody
	public MsgModel deleteUser(@RequestParam HashMap<String, Object> params) {
		try {
			String userIds = (String) params.get("userIds");
			String array[] = userIds.split(",");
			for (String userId : array) {
				params.put("userId", userId);
				SysUserKey user = new SysUserKey();
				user.setUserId(userId);
				int rows = mapper.deleteByPrimaryKey(user);
				if(rows<1){
					 return this.resultMsg("-9999", "删除失败");
				}
			}
			return this.resultMsg("0", "删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			return this.resultMsg("-9999", "删除失败");
		}

	}
    /**
     * 用户添加保存<br>
     *
     * @param userId  用户Id
     * @return MsgModel 消息模型
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public MsgModel save(SysUser record) {
    	try{
    		int result = 0;
    		if(this.isNull(record.getUserId())){
    			
    			record.setUserId(this.getUUID());
    			 String passwd = new  SimpleHash("SHA-1",record.getUserCode(),record.getUserPassword()).toString();
    			 record.setUserPassword(passwd);
    			 record.setUserType("");
    			result = mapper.insertSelective(record);
    		} else{
    			result = mapper.updateByPrimaryKeySelective(record);
    		}
        	if(result<1){
			 return this.resultMsg("-9999", "保存失败，账户名不可修改");
        	}
            return this.resultMsg("0","保存成功");
    	}catch (Exception e){
    		e.printStackTrace();
    		return this.resultMsg("-9999","保存失败");
    	}
    	
    }
    
    
    /**
     *
     * @param userId  用户Id
     * @return MsgModel 消息模型
     */
    @RequestMapping(value = "/getLoginUser", method = RequestMethod.POST)
    @ResponseBody
    public MsgModel getLoogin() {
    	try{
    		LoginUser loginUser = this.getSessionUser();
    		String userName =loginUser.getUserCode();
    		String loginId =loginUser.getUserId();
            return this.resultMsg("0","获取登陆用户成功",loginUser);
    	}catch (Exception e){
    		e.printStackTrace();
    		return this.resultMsg("-9999","保存失败");
    	}
    	
    }
    
    
    
    /**
     * 根据id获取将要编辑的用户数据
     * @param params
     * @return
     */
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @ResponseBody
	public MsgModel updatePassword(SysUser record) {
		try {
			String userCode = record.getUserCode();
			String password = record.getUserPassword();
			String passwd = new  SimpleHash("SHA-1",userCode,password).toString();
			record.setUserPassword(passwd);
			int result = mapper.updateByPrimaryKeySelective(record);
			if(result<1){
				return this.resultMsg("-9999", "密码初始化失败");
			}
			return this.resultMsg("0", "密码初始化成功");
		} catch (Exception e) {
			e.printStackTrace();
			return this.resultMsg("-9999", "密码初始化失败");
		}

	}
    /**
     * 跳转密码修改页面
     * @return
     */
    @RequestMapping("/personal")
    public String personal() {
        return "common/personal/manage";
    }
    
    @RequestMapping(value = "/getPer", method = RequestMethod.POST)
    @ResponseBody
    public MsgModel getPer() {
    	LoginUser loginUser = this.getSessionUser();
    	return this.resultMsg("0", "成功获取登陆用户信息",loginUser);
    }
    
    /**
     * 根据id获取将要编辑的用户数据
     * @param params
     * @return
     */
    @RequestMapping(value = "/updatePerPassword", method = RequestMethod.POST)
    @ResponseBody
	public MsgModel updatePerPassword(@RequestParam HashMap<String, Object> params) {
		try {
			LoginUser loginUser = this.getSessionUser();
			
			String userCode =loginUser.getUserCode();
			String oldPassword = (String) params.get("oldPassword");
			String newPassword = (String) params.get("newPassword");
			String confirmPassword = (String) params.get("confirmPassword");
			
			String newPasswd = new  SimpleHash("SHA-1",userCode,newPassword).toString();
			String oldPasswd = new  SimpleHash("SHA-1",userCode,oldPassword).toString();
			if(!oldPasswd.equals(loginUser.getUserPassword())){
				return this.resultMsg("-1", "原密码错误");
			}
			if(!confirmPassword.equals(newPassword)){
				return this.resultMsg("-1", "两次输入密码不一致");
			}
			if(oldPasswd.equals(newPasswd)){
				return this.resultMsg("-1", "新修改的密码与原来的密码不能一致");
			}
			params.put("userId", loginUser.getUserId());
			params.put("userPassword", newPasswd);
			/*sysUserService.updatePassword( params);  */
			SysUser record = new SysUser();
			record.setUserId(loginUser.getUserId());
			record.setUserCode(loginUser.getUserCode());
			record.setUserPassword(newPasswd);
			int result = mapper.updateByPrimaryKeySelective(record);
			if(result<1){
				return this.resultMsg("0", "密码修改失败,请重新登录系统");
			}
			Subject subject = SecurityUtils.getSubject();
	        subject.logout();
			return this.resultMsg("0", "密码修改成功,请重新登录系统");
		} catch (Exception e) {
			e.printStackTrace();
			return this.resultMsg("-9999", "密码修改失败");
		}

	}
}
